<template>
  <div class="designer-container">
    <div class="canvas-container">
      <div ref="canvasRef" class="canvas"></div>
      <properties-panel 
        v-if="modeler && element" 
        :modeler="modeler" 
        :element="element" 
      />
    </div>
    <div id="js-properties-panel" class="properties-panel-container"></div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import BpmnModeler from 'bpmn-js/lib/Modeler';
import PropertiesPanel from './PropertiesPanel.vue';
import tokenSimulation from 'bpmn-js-token-simulation';
import createAppendAnything from 'bpmn-js-create-append-anything';
import lintModule from 'bpmn-js-bpmnlint';
import colorPickerModule from 'bpmn-js-color-picker';

import { customPaletteProvider } from './paletteProvider';
import { defaultFlowableTemplate } from '@/utils/flowableUtils';

const canvasRef = ref<HTMLElement>();
const modeler = ref<BpmnModeler>();
const element = ref<any>(null);

const initModeler = async () => {
  if (!canvasRef.value) return;
  
  modeler.value = new BpmnModeler({
    container: canvasRef.value,
    additionalModules: [
      tokenSimulation, 
      createAppendAnything,
      lintModule,
      colorPickerModule,
      customPaletteProvider
    ],
    propertiesPanel: {
      parent: '#js-properties-panel'
    },
    moddleExtensions: {
      
    }
  });

  try {
    await modeler.value.importXML(defaultFlowableTemplate);
    
    modeler.value.on('selection.changed', (e) => {
      element.value = e.newSelection[0] || null;
    });
    
    modeler.value.on('element.changed', (e) => {
      console.log('Element changed', e.element);
    });
    
    // 激活令牌模拟器
    modeler.value.get('simulation').toggle();
  } catch (err) {
    console.error('Error initializing BPMN Modeler', err);
  }
};

const getXML = async () => {
  if (!modeler.value) return '';
  const { xml } = await modeler.value.saveXML({ format: true });
  return xml;
};

const getSVG = async () => {
  if (!modeler.value) return '';
  const { svg } = await modeler.value.saveSVG();
  return svg;
};

onMounted(initModeler);
onBeforeUnmount(() => {
  if (modeler.value) modeler.value.destroy();
});

defineExpose({ getXML, getSVG });
</script>

<style>
.designer-container {
  display: flex;
  height: 100%;
  overflow: hidden;
  background: #fff;
}

.canvas-container {
  flex: 1;
  display: flex;
  position: relative;
  overflow: hidden;
}

.canvas {
  flex: 1;
  height: 100%;
}

.properties-panel-container {
  width: 320px;
  background: #f8f9fa;
  border-left: 1px solid #dee2e6;
  overflow-y: auto;
}

/* 流程模拟样式 */
.simulation-overlay {
  z-index: 1000 !important;
}

/* 校验错误标记 */
.bpmn-error-marker {
  background: rgba(220, 53, 69, 0.2);
  border: 2px solid #dc3545;
}
</style>